<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :width="700">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './deviceType.data';
  import { list, saveOrUpdateDeviceType, getDeviceTypeById } from './deviceType.api';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    
    //获取下拉树信息
    const result = await list();
    const treeData = result.data ? result.data : [];
    treeData.unshift({id:'0', name:'请选择父类型'});

    updateSchema([
      {
        field: 'pid',
        componentProps: { treeData },
      },
    ]);

    if (unref(isUpdate)) {
      //获取详情
      data.record = await getDeviceTypeById({ id: data.record.id });
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }

    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      let values = { ...data.record };
      setFieldsValue(values);
    }
  });
  //设置标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增设备类型' : '编辑设备类型'));
  //表单提交事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdateDeviceType(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
